<?php
class SaveFragment extends Action {
	/*
	 * (non-PHPdoc) @see Action::execute()
	 */
	public function execute($params) {
		$I = check_login ( ADMIN_LOGIN_PAGE );
		 
		$fragment = rqsts ( array ('fragment_id' => 0,'title','name','note','fragment' => '' ), true );
		$fragModel = new WebFragmentModel ();
		
		if (empty ( $fragment ['fragment_id'] )) { // 新增
			unset ( $fragment ['fragment_id'] );
			$fragment['create_uid'] = $I->uid;
		}
		$fragment ['fragment'] = htmlspecialchars ( $fragment ['fragment'] ); // 编码
		                                                                      // 验证用户数据的合法性
		$valid = $this->validate ( 'fragment', $fragment, $fragModel );
		$fragment['update_uid'] = $I->uid;
		if ($valid === true) { // 用户数据合法
			$rst = $fragModel->save ( $fragment );
			if (! empty ( $rst )) {
				sess_add ( 'page_tip_info', '<strong>恭喜,</strong>代码片断已经保存完成.' );
				$fragment ['fragment_id'] = $rst ['fragment_id'];
				sess_add ( 'fragment_form_data', $fragment );
				Response::redirect ( './?Ctlr=EditFrag&suc=1&fid=' . $rst ['fragment_id'] );
			} else {
				sess_add ( 'fragment_form_data', $fragment );
				sess_add ( 'page_tip_info', '<strong>出错啦!</strong>' . $fragModel->last_error_msg () );
				Response::redirect ( $this->referer );
			}
		}
		sess_add ( 'page_tip_info', '<strong>出错啦!</strong>' . implode ( '<br/>', $valid ) );
		sess_add ( 'fragment_form_data', $fragment );
		Response::redirect ( $this->referer );
	}
}